//封装本地储存相关方法的类
export class LocalCache {
  setCache(key: string, value: any) {
    if (typeof value === 'object') {
      window.localStorage.setItem(key, JSON.stringify(value))
      return
    }
    window.localStorage.setItem(key, value)
  }

  getCache: getLocalStorageType = (key: string, jsonTransform?: boolean) => {
    const localString = localStorage.getItem(key)
    if (!localString || !jsonTransform) return localString
    try {
      return JSON.parse(localString)
    } catch (error) {
      console.log(`[${key}] 为非法JSON字符串`, { key, value: localString })
      return null
    }
  }

  deleteCache(key: string) {
    window.localStorage.removeItem(key)
  }

  clearCache() {
    window.localStorage.clear()
  }
}
export default new LocalCache()
